package com.kedacom.demo.utils;

import java.io.IOException;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;

/**
 * JacksonUtils
 * @author luocanfeng
 * @date 2015年3月5日
 */
public class JacksonUtils {

	private static final ObjectMapper objectMapper;
	private static final JaxbAnnotationModule jaxbAnnotationModule;

	static {
		jaxbAnnotationModule = new JaxbAnnotationModule();

		objectMapper = new ObjectMapper();
		objectMapper.registerModule(jaxbAnnotationModule);
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

	public static String toJsonString(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <T> T fromJsonStringSilently(String jsonString, Class<T> clazz) {
		try {
			return objectMapper.readValue(jsonString, clazz);
		} catch (IOException e) {
			return null;
		}
	}

	public static <T> T fromJsonString(String jsonString, Class<T> clazz) {
		try {
			return objectMapper.readValue(jsonString, clazz);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

}
